<template>
  <div class="register-source">
    <div class="drawer-wrap" :class="{ disabled: !editable }" v-loading="loading">
      <div class="drawer-content tag-scrollbar">
        <el-form :model="editForm" label-width="0" :rules="editFormRules" ref="editForm">
          <template v-if="editForm.tagKind !== 5">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-purpose">数据源</div>
                  <div class="source-content">
                    <el-form-item prop="plfmId">
                      <el-select v-model="editForm.plfmId" :disabled="!editable" filterable clearable>
                        <el-option label="---" value=""></el-option>
                        <el-option
                          v-for="item in platforms"
                          :key="item.plfmId"
                          :label="item.plfmNm"
                          :value="item.plfmId"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-purpose">数据库</div>
                  <div class="source-content">
                    <el-form-item prop="dbNm">
                      <el-select v-model="editForm.dbNm" :disabled="!editable" filterable clearable>
                        <el-option label="---" value=""></el-option>
                        <el-option
                          v-for="item in dbList"
                          :key="item.dbId"
                          :label="item.dbName"
                          :value="item.dbName"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-blue">数据表</div>
                  <div class="source-content">
                    <el-form-item prop="tableNm">
                      <el-select v-model="editForm.tableNm" :disabled="!editable" filterable clearable>
                        <el-option label="---" value=""></el-option>
                        <el-option
                          v-for="item in tableList"
                          :key="item.tableId"
                          :label="item.tableNm"
                          :value="item.tableNm"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="source-item">
                  <div class="star"></div>
                  <div class="source-title linear-blue">{{ editForm.tagKind === 4 ? '事件ID' : '字段' }}</div>
                  <div class="source-content">
                    <el-form-item prop="fieldNm">
                      <el-input placeholder="请输入字段" v-model="editForm.fieldNm" :disabled="!editable"></el-input>
                    </el-form-item>
                  </div>
                </div>
              </el-col>
            </el-row>
          </template>
          <el-row :gutter="20">
            <el-col :span="12" v-if="editForm.tagKind === 5">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-cyan">字段</div>
                <div class="source-content">
                  <el-form-item prop="fieldNm">
                    <el-input placeholder="请输入字段" v-model="editForm.fieldNm" :disabled="!editable"></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12" v-else>
              <div class="source-item">
                <div class="source-title linear-cyan">关联字段</div>
                <div class="source-content rela-content">
                  <el-form-item prop="relaFields">
                    {{ editForm.relaFields.join(',') }}
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12" v-if="editForm.tagKind !== 4">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-cyan">取值类型</div>
                <div class="source-content">
                  <el-form-item prop="valueType">
                    <el-select v-model="editForm.valueType" :disabled="!editable" @change="changeType">
                      <el-option label="---" value=""></el-option>
                      <el-option
                        v-for="item in $dictList('value_type')"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-red">更新频率</div>
                <div class="source-content">
                  <el-form-item prop="updateFreq">
                    <el-select v-model="editForm.updateFreq" :disabled="!editable" @change="clearUpdateValue">
                      <el-option
                        v-for="dict in $dictList('update_freq')"
                        :key="dict.key"
                        :value="dict.key"
                        :label="dict.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="source-item">
                <div class="source-title linear-red">
                  更新规则
                  <freq-tips></freq-tips>
                </div>
                <div class="source-content">
                  <el-form-item
                    prop="updateFreqValue"
                    :rules="editForm.updateFreq === 1 ? { validator: numberRules, trigger: 'blur' } : {}"
                  >
                    <el-date-picker
                      v-model="editForm.updateFreqValue"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择日期"
                      :picker-options="editForm.updateFreq === 0 ? pickOptions : MonthPickOptions"
                      :disabled="!editable"
                      v-if="editForm.updateFreq === 0 || editForm.updateFreq === 4"
                    ></el-date-picker>
                    <el-input
                      v-model="editForm.updateFreqValue"
                      placeholder="请输入更新规则"
                      :disabled="!editable"
                      v-else-if="editForm.updateFreq === 1"
                    ></el-input>
                    <el-select v-model="editForm.updateFreqValue" :disabled="!editable" v-else>
                      <el-option label="---" value=""></el-option>
                      <template v-if="editForm.updateFreq === 2">
                        <el-option v-for="item in 7" :key="item" :label="item" :value="item.toString()"></el-option>
                      </template>
                      <template v-else-if="editForm.updateFreq === 3">
                        <el-option label="月末" value="0"></el-option>
                        <el-option v-for="item in 28" :key="item" :label="item" :value="item.toString()"></el-option>
                      </template>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="editForm.tagKind !== 5 && editForm.syncRecords.length">
            <el-col :span="24">
              <div class="source-item sync-item">
                <div class="source-title linear-blue"><span>数据同步</span></div>
                <div class="source-content">
                  <el-row class="sync-row-title">
                    <el-col :span="6">同步平台</el-col>
                    <el-col :span="6">同步数据库</el-col>
                    <el-col :span="6">同步数据表</el-col>
                    <el-col :span="6">同步字段</el-col>
                  </el-row>
                  <el-row v-for="(item, index) in editForm.syncRecords" :key="item.plfmId">
                    <el-col :span="6">
                      <el-form-item :prop="`syncRecords[${index}].checked`">
                        <el-checkbox v-model="item.checked" :disabled="!editable" @change="changeSync($event, index)">{{
                          item.syncPlfmNm
                        }}</el-checkbox>
                      </el-form-item>
                    </el-col>
                    <!-- <el-col :span="5">{{ item.syncPlfmNm }}</el-col> -->
                    <el-col :span="6">
                      <el-form-item
                        :prop="`syncRecords[${index}].syncDbNm`"
                        :rules="{
                          validator: checkSyncForm,
                          trigger: 'blur'
                        }"
                      >
                        <el-input v-model="item.syncDbNm" :disabled="!item.checked"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        :prop="`syncRecords[${index}].syncTableNm`"
                        :rules="{
                          validator: checkSyncForm,
                          trigger: 'blur'
                        }"
                      >
                        <el-input v-model="item.syncTableNm" :disabled="!item.checked"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        :prop="`syncRecords[${index}].syncFieldNm`"
                        :rules="{
                          validator: checkSyncForm,
                          trigger: 'blur'
                        }"
                      >
                        <el-input v-model="item.syncFieldNm" :disabled="!item.checked"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="params-selection">
                <div class="star"></div>
                <el-form-item label="是否枚举：" label-width="120px" prop="enumTag">
                  <el-radio-group v-model="editForm.enumTag" :disabled="!editable || editForm.valueType != 1">
                    <el-radio :label="1">
                      是
                    </el-radio>
                    <el-radio :label="0">
                      否
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
          </el-row>

          <template v-if="editForm.enumTag === 1">
            <div class="params">
              <el-form-item label="添加方式：" label-width="120px" prop="isEnumImport">
                <el-radio-group
                  v-model="editForm.isEnumImport"
                  :disabled="!editable || editForm.astTagEnumValList.length >= 30"
                >
                  <el-radio :label="false">
                    立即填写
                  </el-radio>
                  <el-radio :label="true">
                    批量导入
                  </el-radio>
                </el-radio-group>
                <span class="tips">如枚举值过多，建议使用批量导入方式添加</span>
              </el-form-item>
              <template v-if="!editForm.isEnumImport">
                <el-row :gutter="20" class="params-title">
                  <el-col :span="10">枚举值</el-col>
                  <el-col :span="10">描述</el-col>
                </el-row>
                <el-row
                  :gutter="20"
                  v-for="(item, index) in editForm.astTagEnumValList"
                  :key="'astTagEnumValList' + index"
                >
                  <el-col :span="10">
                    <el-form-item
                      :prop="'astTagEnumValList.' + index + '.cdVal'"
                      :rules="[
                        {
                          required: true,
                          message: '枚举值不能为空',
                          trigger: 'blur'
                        },
                        { max: 100, message: '枚举值不能超过100个字符', trigger: 'blur' }
                      ]"
                    >
                      <el-input
                        v-model="item.cdVal"
                        :placeholder="'枚举值' + (index + 1)"
                        :disabled="!editable"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="10">
                    <el-form-item
                      :prop="'astTagEnumValList.' + index + '.cdDesc'"
                      label-width="0"
                      :rules="{ max: 500, message: '描述不能超过500个字符', trigger: 'blur' }"
                    >
                      <el-input v-model="item.cdDesc" placeholder="描述" :disabled="!editable"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="4" v-if="editable">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      size="mini"
                      circle
                      @click="addParams('astTagEnumValList')"
                    ></el-button>
                    <el-button
                      type="warning"
                      icon="el-icon-minus"
                      size="mini"
                      circle
                      @click="remove('astTagEnumValList', index)"
                      v-if="index !== 0"
                    ></el-button>
                  </el-col>
                </el-row>
              </template>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="params-selection">
                <div class="star"></div>
                <el-form-item label="是否带参数：" label-width="120px" prop="haveParam">
                  <el-radio-group v-model="editForm.haveParam" :disabled="!editable">
                    <el-radio :label="1">
                      是
                    </el-radio>
                    <el-radio :label="0">
                      否
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <template v-if="editForm.haveParam === 1">
            <div class="params">
              <el-row :gutter="20" class="params-title">
                <el-col :span="5">参数名称</el-col>
                <el-col :span="4">参数类型</el-col>
                <el-col :span="2">是否枚举</el-col>
                <el-col :span="4">参数字段</el-col>
                <el-col :span="5">可选参数值</el-col>
              </el-row>
              <el-row :gutter="20" v-for="(item, index) in editForm.astTagParamList" :key="'astTagParamList' + index">
                <el-col :span="5">
                  <el-form-item
                    :prop="'astTagParamList.' + index + '.paramNm'"
                    :rules="[
                      {
                        required: true,
                        message: '参数名称不能为空',
                        trigger: 'blur'
                      },
                      { max: 100, message: '参数名称不能超过100个字符', trigger: 'blur' }
                    ]"
                  >
                    <el-input v-model="item.paramNm" placeholder="参数名称" :disabled="!editable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item
                    :prop="'astTagParamList.' + index + '.paramType'"
                    :rules="{
                      required: true,
                      message: '参数类型不能为空',
                      trigger: 'change'
                    }"
                    label-width="0"
                  >
                    <el-select v-model="item.paramType" :disabled="!editable">
                      <el-option label="---" value=""></el-option>
                      <el-option
                        v-for="item in $dictList('value_type')"
                        :key="item.key"
                        :label="item.value"
                        :value="item.key"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="2" align="center">
                  <el-form-item :prop="'astTagParamList.' + index + '.enumTag'" label-width="0">
                    <el-checkbox v-model="item.enumTag" :true-label="1" :false-label="0"></el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item
                    :prop="'astTagParamList.' + index + '.fieldNm'"
                    :rules="{
                      required: true,
                      message: '参数字段不能为空',
                      trigger: 'blur'
                    }"
                    label-width="0"
                  >
                    <el-input v-model="item.fieldNm" placeholder="参数字段" :disabled="!editable"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="5" :align="item.enumTag === 1 ? 'none' : 'center'">
                  <el-form-item
                    :prop="'astTagParamList.' + index + '.optParamVal'"
                    :rules="item.enumTag === 1 ? { required: true, message: '参数值不能为空', trigger: 'change' } : {}"
                  >
                    <el-input
                      v-model="item.optParamVal"
                      placeholder="可选参数值"
                      readonly
                      class="enums-box"
                      v-if="item.enumTag === 1"
                      @click.native="$refs.enumsDialog.showDialog({ optParamVal: item.optParamVal, index: index })"
                    ></el-input>
                    <span v-else>---</span>
                  </el-form-item>
                </el-col>
                <el-col :span="4" v-if="editable">
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    circle
                    @click="addParams('astTagParamList')"
                  ></el-button>
                  <el-button
                    type="warning"
                    icon="el-icon-minus"
                    size="mini"
                    circle
                    @click="remove('astTagParamList', index)"
                    v-if="index !== 0"
                  ></el-button>
                </el-col>
              </el-row>
            </div>
          </template>
          <template v-if="editForm.tagKind === 5">
            <el-button :type="editable ? 'primary' : 'info'" @click="showManualDrawer">导入手工标签数据</el-button>
            <span class="manual-tips" v-if="editForm.plfmId">
              <icon-svg name="iconComplete"></icon-svg>
              导入成功
            </span>
            <!-- <span class="deleteBtn" v-if="editForm.plfmId">
              <el-tooltip effect="dark" content="删除旧数据" placement="top">
                <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="removeTable"></el-button>
              </el-tooltip>
            </span> -->
          </template>
          <template v-if="astTagRequireStatusList.length">
            <div class="content-divider second">
              <div class="clearfix">
                <div class="number">01</div>
                <div class="divider-title">注册状态<br />Register status</div>
                <div class="bg"></div>
              </div>
            </div>
            <ul class="tag-status-list">
              <li v-for="(item, index) in astTagRequireStatusList" :key="index">
                <el-row :gutter="20">
                  <el-col :span="5">{{ $name(item, 'handlerNnm', 'handlerNm') }}</el-col>
                  <el-col :span="5">{{ item.nodeNm }}</el-col>
                  <el-col :span="7">{{ item.procTm }}</el-col>
                  <el-col :span="7">{{ item.handlerCmnt }}</el-col>
                </el-row>
              </li>
            </ul>
          </template>
        </el-form>
      </div>
    </div>
    <div class="drawer-btns" v-if="editable">
      <!-- <el-button type="primary" size="medium" class="preview">预览</el-button> -->
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" size="medium" @click="handlePrev">上一步</el-button>
      <el-button type="primary" size="medium" @click="handleSave(false)">保存为草稿</el-button>
      <el-button type="primary" size="medium" @click="handleSave(true)">下一步</el-button>
    </div>
    <enums-dialog ref="enumsDialog" @updateParams="updateParams"></enums-dialog>
    <register-manual-drawer ref="registerManualDrawer" @callback="setManualData"></register-manual-drawer>
  </div>
</template>

<script>
import enumsDialog from '@/components/tag-enums-dialog'
import registerManualDrawer from '../batch/register-manual-batch'
import freqTips from '@/components/tag-freq-tips'
export default {
  components: {
    enumsDialog,
    registerManualDrawer,
    freqTips
  },
  props: {
    tagId: {
      type: String,
      required: true,
      default: ''
    }
  },
  data() {
    return {
      firstLoad: true,
      editable: false,
      loading: false,
      platforms: [],
      dbList: [],
      tableList: [],
      editForm: {
        plfmId: '',
        dbNm: '',
        tableNm: '',
        fieldNm: '',
        relaFields: [],
        valueType: '',
        updateFreq: '',
        updateFreqValue: '',
        syncRecords: [],
        enumTag: '',
        astTagEnumValList: [{ cdVal: '', cdDesc: '' }],
        haveParam: '',
        astTagParamList: [{ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' }],
        isEnumImport: false,
        tagKind: ''
      },
      astTagRequireStatusList: [],
      editFormRules: {
        plfmId: [{ required: true, message: '平台不能为空', trigger: 'change' }],
        dbNm: [{ required: true, message: '数据库不能为空', trigger: 'change' }],
        tableNm: [{ required: true, message: '数据表不能为空', trigger: 'change' }],
        fieldNm: [{ required: true, message: '字段不能为空', trigger: 'blur' }],
        valueType: [{ required: true, message: '取值类型不能为空', trigger: 'change' }],
        updateFreq: [{ validator: this.$checkBoolNum('更新频率必须选择'), trigger: 'change' }],
        enumTag: [{ validator: this.$checkBoolNum('是否枚举必须选择'), trigger: 'change' }],
        haveParam: [{ validator: this.$checkBoolNum('是否带参数必须选择'), trigger: 'change' }]
      },
      numberRules: (rule, value, callback) => {
        if (value === '') callback()
        else {
          if (isNaN(value)) callback(new Error('只能输入大于0的正整数'))
          else {
            if (Number(value) > 0) {
              if (Number(value) % 1 === 0) callback()
              else callback(new Error('只能输入大于0的正整数'))
            } else callback(new Error('只能输入大于0的正整数'))
          }
        }
      },
      checkSyncForm: (rule, value, callback) => {
        let field = rule.field.split('.')[0]
        let fieldname = field.split('[')[0]
        let index = Number(field.split('[')[1].split(']')[0])
        if (this.editForm[fieldname][index].checked) {
          if (!value) callback(new Error('数据同步项不能为空'))
          else {
            let patt = /^[0-9a-zA-Z_]{1,}$/
            if (!patt.test(value)) {
              callback(new Error('数据同步项只能输入字母数字和下划线'))
            } else {
              const avalue = [...new Set(value.trim().split(''))]
              if (!isNaN(value)) {
                callback(new Error('数据同步项不能为纯数字'))
              } else if (!isNaN(value.substr(0, 1))) {
                callback(new Error('数据同步项首字母不能为数字'))
              } else if (avalue.length == 1 && avalue[0] === '_') {
                callback(new Error('数据同步项不能为纯下划线'))
              } else callback()
            }
          }
        } else callback()
      },
      pickOptions: {
        disabledDate(time) {
          return time.getTime() > new Date().getTime()
        }
      },
      MonthPickOptions: {
        disabledDate(time) {
          const year = new Date().getFullYear()
          const beginTime = new Date(year - 1 + '-12-31 23:59:59')
          const endTime = new Date(year + '-12-31 23:59:59')
          return !(time.getTime() > beginTime.getTime() && time.getTime() < endTime.getTime())
        }
      }
    }
  },
  watch: {
    'editForm.plfmId'(val) {
      this.dbList = []
      this.tableList = []
      this.editForm.dbNm = ''
      this.editForm.tableNm = ''
      this.editForm.relaFields = []
      this.initSyncRecords()
      if (val) this.getDbList()
    },
    'editForm.dbNm'(val) {
      this.tableList = []
      this.editForm.tableNm = ''
      this.editForm.relaFields = []
      if (val) this.getTableList()
    },
    'editForm.tableNm'(val) {
      this.editForm.relaFields = []
      if (val && !this.firstLoad) this.getRelaFields()
    }
  },
  methods: {
    getSelections() {
      this.getPlatforms()
    },
    initSyncRecords() {
      let index = this.editForm.syncRecords.findIndex(item => item.syncPlfmId === this.editForm.plfmId)
      if (index >= 0) this.editForm.syncRecords.splice(index, 1)
      this.platforms.forEach(platform => {
        if (
          platform.plfmId !== this.editForm.plfmId &&
          !this.editForm.syncRecords.find(item => item.syncPlfmId === platform.plfmId)
        ) {
          this.editForm.syncRecords.push({
            checked: false,
            syncPlfmId: platform.plfmId,
            syncPlfmNm: platform.plfmNm,
            syncDbNm: '',
            syncTableNm: '',
            syncFieldNm: ''
          })
        }
      })
    },
    changeSync(val, index) {
      if (!val) {
        this.editForm.syncRecords[index].syncDbNm = ''
        this.editForm.syncRecords[index].syncTableNm = ''
        this.editForm.syncRecords[index].syncFieldNm = ''
      }
    },
    changeType(val) {
      if (val != 1) this.editForm.enumTag = 0
    },
    showManualDrawer() {
      if (this.editable) this.$refs.registerManualDrawer.showDrawer(this.tagId)
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagRegister/readNode'),
        method: 'get',
        params: this.$ajax.setParams({
          tagIds: this.tagId
        })
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editable = data.data.editable
          this.editForm.tagKind = data.data.astRegisterFirstReadDTO.astTagDTO.tagKind
          if (data.data.astRegisterSecondReadDTO.astTagDataRela) {
            this.editForm.plfmId = data.data.astRegisterSecondReadDTO.astTagDataRela.plfmId
            this.editForm.valueType = data.data.astRegisterSecondReadDTO.astTagDataRela.valueType
            this.editForm.updateFreq = data.data.astRegisterSecondReadDTO.astTagDataRela.updateFreq
            this.editForm.updateFreqValue = data.data.astRegisterSecondReadDTO.astTagDataRela.updateFreqValue
              ? this.editForm.updateFreq === 4
                ? new Date().getFullYear() + '-' + data.data.astRegisterSecondReadDTO.astTagDataRela.updateFreqValue
                : data.data.astRegisterSecondReadDTO.astTagDataRela.updateFreqValue
              : ''
            this.editForm.enumTag = data.data.astRegisterSecondReadDTO.astTagDataRela.enumTag
            this.editForm.astTagEnumValList = data.data.astRegisterSecondReadDTO.astTagEnumVal.length
              ? data.data.astRegisterSecondReadDTO.astTagEnumVal
              : [{ cdVal: '', cdDesc: '' }]
            if (
              (data.data.astRegisterSecondReadDTO.astTagDataRela.enumTag === 1 &&
                !data.data.astRegisterSecondReadDTO.astTagEnumVal.length) ||
              data.data.astRegisterSecondReadDTO.astTagEnumVal.length > 10
            )
              this.editForm.isEnumImport = true
            this.editForm.haveParam = data.data.astRegisterSecondReadDTO.astTagDataRela.haveParam
            this.editForm.astTagParamList = data.data.astRegisterSecondReadDTO.astTagParam.length
              ? data.data.astRegisterSecondReadDTO.astTagParam
              : [{ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' }]
            this.editForm.fieldNm = data.data.astRegisterSecondReadDTO.astTagDataRela.fieldNm
            this.$nextTick(() => {
              this.editForm.dbNm = data.data.astRegisterSecondReadDTO.astTagDataRela.dbNm
              this.$nextTick(() => {
                this.editForm.tableNm = data.data.astRegisterSecondReadDTO.astTagDataRela.tableNm
                this.$nextTick(() => {
                  this.editForm.relaFields = data.data.astRegisterSecondReadDTO.relaFields
                  this.firstLoad = false
                })
              })
            })
          } else {
            this.firstLoad = false
          }
          this.$nextTick(() => {
            // 同步数据
            data.data.astRegisterSecondReadDTO.syncRecords.forEach(item => {
              let index = this.editForm.syncRecords.findIndex(value => value.syncPlfmId === item.syncPlfmId)
              if (index >= 0) {
                this.editForm.syncRecords[index].checked = true
                this.editForm.syncRecords[index].syncDbNm = item.syncDbNm
                this.editForm.syncRecords[index].syncFieldNm = item.syncFieldNm
                this.editForm.syncRecords[index].syncTableNm = item.syncTableNm
              }
            })
          })
          this.astTagRequireStatusList = data.data.astTagRequireStatusList || []
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getPlatforms() {
      this.$ajax({
        url: this.$ajax.setUrl('mta/mtaPlatform/getAll'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.platforms = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getDbList() {
      this.$ajax({
        url: this.$ajax.setUrl(`mta/mtaDatabase/plfmId/${this.editForm.plfmId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.dbList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getTableList() {
      this.$ajax({
        url: this.$ajax.setUrl(`mta/mtaTable/getTableList/${this.editForm.plfmId}/${this.editForm.dbNm}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.tableList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getRelaFields() {
      this.$ajax({
        url: this.$ajax.setUrl(
          `mta/mtaField/getRelaFieldList/${this.editForm.plfmId}/${this.editForm.dbNm}/${this.editForm.tableNm}`
        ),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.relaFields = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    addParams(name) {
      if (name === 'astTagEnumValList') this.editForm[name].push({ cdVal: '', cdDesc: '' })
      else this.editForm[name].push({ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' })
    },
    remove(name, index) {
      this.editForm[name].splice(index, 1)
    },
    updateParams(opt, index) {
      this.editForm.astTagParamList[index].optParamVal = opt
    },
    handleCancel() {
      this.clearForm()
      this.$emit('close')
    },
    clearUpdateValue() {
      this.editForm.updateFreqValue = ''
    },
    clearForm() {
      this.editable = false
      this.firstLoad = true
      this.loading = false
      this.platforms = []
      this.editForm = {
        plfmId: '',
        dbNm: '',
        tableNm: '',
        fieldNm: '',
        relaFields: [],
        valueType: '',
        itStmt: '',
        updateFreq: '',
        updateFreqValue: '',
        syncRecords: [],
        enumTag: '',
        tagKind: '',
        astTagEnumValList: [{ cdVal: '', cdDesc: '' }],
        isEnumImport: false,
        haveParam: '',
        astTagParamList: [{ fieldNm: '', paramNm: '', paramType: '', enumTag: 0, optParamVal: '' }],
        handlerId: ''
      }
      this.astTagRequireStatusList = []
      this.$refs.editForm.clearValidate()
    },
    handleSave(isSubmit = false) {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          if (this.editForm.tagKind === 5) {
            if (!this.editForm.plfmId) {
              this.$message.error('请先导入手工标签数据！')
              return
            }
          }
          this.loading = true
          let url = isSubmit ? 'ast/astTagRegister/secondSubmit' : 'ast/astTagRegister/secondSave'
          this.editForm.astTagEnumValList.forEach(v => (v.tagId = this.tagId))
          this.editForm.astTagParamList.forEach(v => {
            v.plfmId = this.editForm.plfmId
            v.dbName = this.editForm.dbNm
            v.tableNm = this.editForm.tableNm
            v.tagId = this.tagId
          })
          let syncRecords = []
          this.editForm.syncRecords.forEach(item => {
            if (item.checked)
              syncRecords.push({
                syncDbNm: item.syncDbNm,
                syncFieldNm: item.syncFieldNm,
                syncPlfmId: item.syncPlfmId,
                syncPlfmNm: item.syncPlfmNm,
                syncTableNm: item.syncTableNm,
                tagId: this.tagId
              })
          })
          this.editForm.astTagParamList.forEach(item => {
            if (!item.enumTag) item.optParamVal = ''
          })
          if (this.editForm.astTagEnumValList.length && !this.editForm.astTagEnumValList[0].cdVal)
            this.editForm.astTagEnumValList.splice(0, 1)
          this.$ajax({
            url: this.$ajax.setUrl(url),
            method: 'post',
            data: this.$ajax.setData({
              astTagEnumValList: this.editForm.astTagEnumValList,
              astTagParamList: this.editForm.astTagParamList,
              dbNm: this.editForm.dbNm,
              enumTag: this.editForm.enumTag,
              fieldNm: this.editForm.fieldNm,
              relaFields: this.editForm.relaFields,
              haveParam: this.editForm.haveParam,
              plfmId: this.editForm.plfmId,
              tagId: this.tagId,
              tableNm: this.editForm.tableNm,
              updateFreq: this.editForm.updateFreq,
              updateFreqValue: this.editForm.updateFreqValue
                ? this.editForm.updateFreq === 4
                  ? this.editForm.updateFreqValue.substring(5)
                  : this.editForm.updateFreqValue
                : '',
              valueType: this.editForm.tagKind === 4 || this.editForm.tagKind === 5 ? 1 : this.editForm.valueType,
              syncRecords: syncRecords
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              if (isSubmit) {
                this.$emit('callback')
              } else {
                this.getDetail()
              }
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    handlePrev() {
      if (this.loading) return
      this.$emit('prev')
    },
    removeTable() {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astData/import/deleteBatchRecords/${this.tagId}`),
        method: 'delete',
        params: this.$ajax.setParams()
      }).then(() => {
        this.editForm.plfmId = ''
        this.editForm.dbNm = ''
        this.editForm.tableNm = ''
      })
    },
    setManualData(data) {
      if (data) {
        this.editForm.plfmId = data.plfmId
        this.$nextTick(() => {
          this.editForm.dbNm = data.dbNm
          this.$nextTick(() => (this.editForm.tableNm = data.tableNm))
        })
      }
    }
  }
}
</script>

<style lang="scss">
.tag-drawer.register-single-drawer {
  .el-drawer__body {
    .drawer-content {
      .params {
        .el-input,
        .el-select {
          width: 100%;
        }
        .el-button {
          margin-top: 5px;
        }
      }
    }
  }
  .register-source {
    .preview {
      float: left;
      margin: 17px 0 0 20px;
    }
    .params-selection {
      margin-top: 10px;
      position: relative;
      box-shadow: #eee 0 0 10px;
    }
    .params {
      padding: 20px;
      box-shadow: #eee 0 0 10px;
      position: relative;
      &:before {
        width: 5px;
        content: '';
        background: linear-gradient(#6464c8, #7173e0);
        position: absolute;
        top: 0;
        left: 0;
        bottom: 0;
      }
      & > .el-form-item:first-child {
        margin-left: -20px;
      }
      .params-title {
        text-align: center;
        margin-bottom: 5px;
      }
      li {
        margin-bottom: 10px;
        & + li {
          padding: 10px 0;
        }
      }
    }
    .source-item {
      width: 100%;
      height: 45px;
      margin-bottom: 20px;
      box-shadow: #eee 0 0 10px;
      position: relative;
      &.sync-item {
        font-size: 14px;
        height: auto;
        .source-title {
          font-size: 16px;
          height: 100%;
          span {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
          }
        }
        .el-input {
          padding: 0 5px !important;
        }
        .el-input__inner {
          height: 35px !important;
          line-height: 35px !important;
          border: 1px solid #dcdfe6 !important;
        }
        .sync-row-title {
          font-size: 16px;
          font-weight: bold;
          text-align: center;
        }
        .el-col {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .source-title {
        font-weight: bold;
        width: 150px;
        padding-left: 50px;
        line-height: 45px;
        color: #fff;
        position: absolute;
        &:before {
          width: 10px;
          height: 10px;
          content: '';
          background-color: #eee9ff;
          border: 2px solid #cfc7ee;
          margin-top: -5px;
          position: absolute;
          top: 50%;
          left: 20px;
          border-radius: 50%;
        }
        &:after {
          width: 0;
          height: 0;
          content: '';
          margin-top: -10px;
          border-top: 10px solid transparent;
          border-bottom: 10px solid transparent;
          position: absolute;
          top: 50%;
          right: -10px;
        }
        &.linear-purpose:after {
          border-left: 10px solid #7c6bed;
        }
        &.linear-blue:after {
          border-left: 10px solid #635fd7;
        }
        &.linear-cyan:after {
          border-left: 10px solid #0696ec;
        }
        &.linear-red:after {
          border-left: 10px solid #c563ee;
        }
      }
      .source-content {
        line-height: 45px;
        padding: 0 30px 0 180px;
        &.rela-content {
          padding-left: 195px;
        }
      }
      .el-select .el-input__inner,
      .el-input .el-input__inner {
        height: 45px;
        line-height: 45px;
        border: 0;
      }
    }
    .manual-tips {
      margin-left: 10px;
      color: $tag-green;
      & + .deleteBtn {
        float: right;
      }
    }
  }
}
</style>
